﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;
using SqlSugar;
using System.Windows.Forms;
using System.IO.Compression;
using System.Globalization;


namespace HtFileSync
{
    public class CopyFiles
    {
        public static void CopyFolder(string sourceFolder, string destinationFolder)
        {
            try
            {
                if (sourceFolder != "" && destinationFolder != "")
                {
                    Directory.CreateDirectory(destinationFolder);

                    foreach (string file in Directory.GetFiles(sourceFolder))
                    {
                        string destinationFilePath = Path.Combine(destinationFolder, Path.GetFileName(file));
                        File.Copy(file, destinationFilePath,true);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            
        }

        public static void CopyDir(string srcPath,string aimPath)
        {
            try
            {
                //检查目标目录是否以目录分割字符结束，如果不是则添加
                //if (aimPath[aimPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
                //{
                //    aimPath += System.IO.Path.DirectorySeparatorChar;
                //}
                //判断目标目录是否存在，如果不存在则新建
                //if (!System.IO.Directory.Exists(aimPath))
                //{
                    System.IO.Directory.CreateDirectory(aimPath);
                //}
                //得到源目录的文件列表，该里面是包含文件以及目录路径的一组数组
                //如果要指向Copy目标文件下面的文件尔不包含目录请使用下面的方法
                //string[] fileLest=Directory.GetFiles(srcPath);
                //遍历所有文件和目录
                foreach (var file in Directory.EnumerateFileSystemEntries(srcPath))
                {
                    //先当作目录处理，如果存在这个目录就递归Copy该目录下面的文件
                    if (System.IO.Directory.Exists(file))
                    {
                        CopyDir(file, Path.Combine(aimPath,System.IO.Path.GetFileName(file)));
                    }
                    //否则Copy文件
                    else
                    {
                        System.IO.File.Copy(file, Path.Combine(aimPath, System.IO.Path.GetFileName(file)), true);
                    }
                }


            }
            catch (Exception e) 
            {
                throw;
            }
        }


        public static void FileBackupC(string sourceFolder, string destinationFolder, bool onlyExt, string? extName, bool isZip, string? zipFormat,bool includeSub)
        {
            
            Program.dbcon = destinationFolder + @"\_HtFileSync_db.sqlit";
            FileDbCfg.CreateDatabase();

           
            //设置是否包含子目录选项
            SearchOption searchOption = new SearchOption();
            if (includeSub)
            {
                searchOption= SearchOption.AllDirectories;
            }

            DirectoryInfo di = new DirectoryInfo(sourceFolder);
            try
            {

                foreach (FileInfo file in di.EnumerateFiles("*", searchOption))
                {
                    //获得相对路径
                    string relativePath = file.FullName.Replace(sourceFolder, "").TrimStart(Path.DirectorySeparatorChar);
                    //查询记录
                    var ffdd = FileDbCfg.db.Queryable<FileSyncdb>().OrderBy(it => it.Id, OrderByType.Desc).First(it => it.FileName == relativePath && it.FileSize == file.Length && it.FileModifyTime == file.LastWriteTime);
                    if (ffdd == null)
                    {

                        if (onlyExt & extName != "") //只备份指定扩展名的文件
                        {
                            char[] separators = [',']; // 定义分隔符为逗号
                            string[] extNamefruits = extName.Split(separators); // 使用Split方法拆分字符串
                            string extension = Path.GetExtension(file.FullName); //获取文件的扩展名
                            // 去掉前导的点号
                            if (!string.IsNullOrEmpty(extension))
                            {
                                extension = extension.TrimStart('.');
                            }
                            // 查找扩展名是否存在于数组中
                            bool found = Array.Exists(extNamefruits, element => element.Equals(extension));
                            if (found)
                            {
                                // 获取要写入的文件目录路径
                                string directoryPath = Path.GetDirectoryName(destinationFolder + @"\" + relativePath);

                                // 如果目录不存在，则创建
                                if (!Directory.Exists(directoryPath))
                                {
                                    Directory.CreateDirectory(directoryPath);
                                }
                                //判断是否用压缩格式保存文件
                                if (isZip)
                                {
                                    using FileStream originalFileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
                                    using FileStream compressedFileStream = File.Create(destinationFolder + @"\" + relativePath + ".gz");
                                    using GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress);
                                    originalFileStream.CopyTo(compressionStream);
                                }
                                else
                                {
                                    file.CopyTo(destinationFolder + @"\" + relativePath, true);
                                }
                                //写入数据库
                                var ddd = FileDbCfg.db.Insertable(new FileSyncdb() { FileName = relativePath, CompletionTime = DateTime.Now, FileSize = file.Length, FileCreateTime = file.CreationTime, FileModifyTime = file.LastWriteTime, IsComplete = true }).ExecuteReturnEntity();

                            }
                        }
                        else //备份所有文件
                        {
                            // 获取要写入的文件目录路径
                            string directoryPath = Path.GetDirectoryName(destinationFolder + @"\" + relativePath);

                            // 如果目录不存在，则创建
                            if (!Directory.Exists(directoryPath))
                            {
                                Directory.CreateDirectory(directoryPath);
                            }
                            //判断是否用压缩格式保存文件
                            if (isZip)
                            {
                                using (FileStream originalFileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
                                {
                                    using (FileStream compressedFileStream = File.Create(destinationFolder + @"\" + relativePath + ".gz"))
                                    {
                                        using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
                                        {
                                            originalFileStream.CopyTo(compressionStream);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                file.CopyTo(destinationFolder + @"\" + relativePath, true);
                            }
                            //写入数据库
                            var ddd = FileDbCfg.db.Insertable(new FileSyncdb() { FileName = relativePath, CompletionTime = DateTime.Now, FileSize = file.Length, FileCreateTime = file.CreationTime, FileModifyTime = file.LastWriteTime, IsComplete = true }).ExecuteReturnEntity();

                        }
                    }

                }

            }
            catch (Exception)
            {
                throw;
            }

        }


        public static void FileBackupD(string sourceFolder, string destinationFolder, bool onlyExt, string? extName, bool isZip, string? zipFormat, bool includeSub)
        {

            Program.dbcon = destinationFolder + @"\_HtFileSync_db.sqlit";
            FileDbCfg.CreateDatabase();

            string nowtime = DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss", CultureInfo.InvariantCulture);

            //设置是否包含子目录选项
            SearchOption searchOption = new SearchOption();
            if (includeSub)
            {
                searchOption = SearchOption.AllDirectories;
            }
            else
            {
                searchOption = SearchOption.TopDirectoryOnly;
            }

            DirectoryInfo di = new DirectoryInfo(sourceFolder);
            try
            {

                foreach (FileInfo file in di.EnumerateFiles("*", searchOption))
                {
                    //获得相对路径
                    string relativePath = file.FullName.Replace(sourceFolder, "").TrimStart(Path.DirectorySeparatorChar);
                    //获取要写入的路径
                    string directoryPath = Path.GetDirectoryName(destinationFolder + @"\" + relativePath);
                    //文件名前加上备份时间
                    string ffname=nowtime+" "+file.Name;
                    string newPath=Path.Combine(directoryPath,ffname);

                    //查询记录
                    var ffdd = FileDbCfg.db.Queryable<FileSyncdb>().OrderBy(it => it.Id, OrderByType.Desc).First(it => it.FileName == relativePath && it.FileSize == file.Length && it.FileModifyTime == file.LastWriteTime);
                    if (ffdd == null)
                    {

                        if (onlyExt & extName != "") //只备份指定扩展名的文件
                        {
                            char[] separators = [',']; // 定义分隔符为逗号
                            string[] extNamefruits = extName.Split(separators); // 使用Split方法拆分字符串
                            string extension = Path.GetExtension(file.FullName); //获取文件的扩展名
                            // 去掉前导的点号
                            if (!string.IsNullOrEmpty(extension))
                            {
                                extension = extension.TrimStart('.');
                            }
                            // 查找扩展名是否存在于数组中
                            bool found = Array.Exists(extNamefruits, element => element.Equals(extension));
                            if (found)
                            {

                                // 如果目录不存在，则创建
                                if (!Directory.Exists(directoryPath))
                                {
                                    Directory.CreateDirectory(directoryPath);
                                }
                                //判断是否用压缩格式保存文件
                                if (isZip)
                                {
                                    using (FileStream originalFileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
                                    {
                                        using (FileStream compressedFileStream = File.Create(newPath + ".gz"))
                                        {
                                            using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
                                            {
                                                originalFileStream.CopyTo(compressionStream);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    file.CopyTo(newPath, true);
                                }
                                //写入数据库
                                var ddd = FileDbCfg.db.Insertable(new FileSyncdb() { FileName = relativePath, CompletionTime = DateTime.Now, FileSize = file.Length, FileCreateTime = file.CreationTime, FileModifyTime = file.LastWriteTime, IsComplete = true }).ExecuteReturnEntity();

                            }
                        }
                        else //备份所有文件
                        {
                            // 如果目录不存在，则创建
                            if (!Directory.Exists(directoryPath))
                            {
                                Directory.CreateDirectory(directoryPath);
                            }
                            //判断是否用压缩格式保存文件
                            if (isZip)
                            {
                                using (FileStream originalFileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
                                {
                                    using (FileStream compressedFileStream = File.Create(newPath + ".gz"))
                                    {
                                        using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
                                        {
                                            originalFileStream.CopyTo(compressionStream);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                file.CopyTo(newPath, true);
                            }
                            //写入数据库
                            var ddd = FileDbCfg.db.Insertable(new FileSyncdb() { FileName = relativePath, CompletionTime = DateTime.Now, FileSize = file.Length, FileCreateTime = file.CreationTime, FileModifyTime = file.LastWriteTime, IsComplete = true }).ExecuteReturnEntity();

                        }
                    }

                }

            }
            catch (Exception)
            {
                throw;
            }

        }


        //删除旧文件
        public static void DeleteOldFile(int d, string destinationFolder)
        {
            DirectoryInfo di = new DirectoryInfo(destinationFolder);
            try
            {
                foreach (FileInfo file in di.EnumerateFiles("*", SearchOption.AllDirectories)) 
                {
                    int i= (DateTime.Now- file.CreationTime).Days;
                    
                    if (i>=d & file.Name!= "_HtFileSync_db.sqlit")
                    {
                        File.Delete(file.FullName); // 删除文件
                        //string relativePath = file.FullName.Replace(destinationFolder, "").TrimStart(Path.DirectorySeparatorChar); //获得相对路径
                        //FileDbCfg.db.Deleteable<FileSyncdb>().Where(it => it.FileName == relativePath).ExecuteCommand();//删除数据库内文件信息
                    }
                }

               
               
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }








    }

   
}
